package in.muton.edushare.components.messaging.recievepanel;

import in.muton.edushare.EduShareSession;
import in.muton.edushare.components.messaging.api.ScheduleMessage;
import in.muton.edushare.components.messaging.util.MessageTypeParser;
import in.muton.edushare.panels.images.ImageWithLink;
import in.muton.edushare.processing.objects.ObjectTypeId;
import in.muton.edushare.schedules.DeleteSchedule;
import in.muton.edushare.schedules.widgets.DateHelper;
import in.muton.edushare.schedules.widgets.DateLabel;
import in.muton.edushare.url.EduShareURLPanel;
import in.muton.edushare.url.EntityPageParams;
import in.muton.edushare.url.URLHelper;
import in.muton.edushare.wicket.models.CayenneList;
import in.muton.edushare.wicket.models.CayenneModel;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.wicket.PageParameters;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.Fragment;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;

import com.edushare.common.constants.ApplicationConstants;
import com.edushare.common.dao.ScheduleDAO;
import com.edushare.common.vo.Messages;
import com.edushare.common.vo.Schedules;
import com.edushare.common.vo.Users;
import com.edushare.common.vo.interfaces.IFileUploadable;

public class ScheduleMessagePanel extends Panel {

	private static final Log log = LogFactory
			.getLog(ScheduleMessagePanel.class);

	public ScheduleMessagePanel(String id, IModel<Messages> model) {
		super(id, model);
		msg = model;
		final IFileUploadable entity = MessageTypeParser.getObject(model
				.getObject().getReceiverId(), model.getObject()
				.getReceiverType());
		init();
		Link<Void> l;
		add(l = new Link<Void>("calendarView") {
			@Override
			public void onClick() {
				Class<? extends WebPage> calendarPage = URLHelper
						.getCalendarPageClass(newSchedule.getObject()
								.getCreatorType());
				
				PageParameters p = EntityPageParams
					.getParams(new CayenneModel<IFileUploadable>(entity));
				int i = p.size();
				p.add(""+(i),""+ new DateHelper(newSchedule.getObject().getSchStart()).getMonth());
				p.add(""+(i+1),""+ new DateHelper(newSchedule.getObject().getSchStart()).getYear());
				setResponsePage(calendarPage, p);
			}
			private static final long serialVersionUID = 7513916809860168879L;
		});
		
		l.add(new Label("calendarName", new Model<String>(){
			private static final long serialVersionUID = 3924056837108228354L;
			@Override
			public String getObject(){
				switch(newSchedule.getObject().getCreatorType()){
				case Messages.RECEIVER_TYPE_UNIVERSITY:
					return "View University Calendar";
				case Messages.RECEIVER_TYPE_DEPARTMENT:
					return "View Department Calendar";
				case Messages.RECEIVER_TYPE_COURSE:
					return "View Course Calendar";
				case Messages.RECEIVER_TYPE_USER:
					return "View My Calendar";
				case Messages.RECEIVER_TYPE_GROUP:
					return "View Group Calendar";
				}
				return "View";
			}
		}));
		
		add(new Link<Void>("delete") {
			@Override
			public void onClick() {
				new DeleteSchedule(newSchedule).delete();
				new ScheduleMessage(newSchedule.getObject(),
						ScheduleMessage.EVT_CANCELLED).send();
			}

			@Override
			public boolean isVisible() {
				if (newSchedule.getObject().getStatus() == Schedules.EVENT_STATUS_CANCELLED)
					return false;

				if (newSchedule.getObject().getSchEnd().getTime() <= (new Date())
						.getTime())
					return false;

				Users user = EduShareSession.get().getLoggedInUser();
				CayenneList<Users> owners = ObjectTypeId.getOwner(msg
						.getObject().getReceiverId(), msg.getObject()
						.getReceiverType());

				if (msg.getObject().getReceiverType() == Messages.RECEIVER_TYPE_USER
						&& msg.getObject().getAllMessageRecipients().contains(
								user))
					return true;

				if (owners.contains(user)) {
					return true;
				}
				return false;
			}

			private static final long serialVersionUID = 2074826442617913571L;
		});

		WebMarkupContainer wmc = new WebMarkupContainer("background");
		add(new ImageWithLink("senderImage", new CayenneModel<IFileUploadable>(
				entity), ApplicationConstants.FILE_SUFFIX_ICON));

		wmc.add(MessageTypeParser.getURLPanel(
				model.getObject().getReceiverId(), model.getObject()
						.getReceiverType(), "name"));

		wmc.add(new Label("msg", message).setEscapeModelStrings(false));
		wmc.add(this.getFragment());
		add(wmc);
		add(new DateLabel("time", newSchedule.getObject()
				.getCreationTimestamp(), 0));
		add(new EduShareURLPanel("creator", new CayenneModel<Users>(newSchedule
				.getObject().getCreatingUser())));

	}

	private void init() {
		String str = this.msg.getObject().getMessage();
		if (str.contains(ScheduleMessage.EVT_CANCELLED))
			msgType = ScheduleMessage.EVT_CANCELLED;
		else if (str.contains(ScheduleMessage.EVT_MODIFY))
			msgType = ScheduleMessage.EVT_MODIFY;
		else if (str.contains(ScheduleMessage.NEW_EVENT))
			msgType = ScheduleMessage.NEW_EVENT;
		initSchedules();
		initMessage();
	}

	public void initSchedules() {
		String msg = this.msg.getObject().getMessage();
		int startIndex = ("<<<EDUSHAREMESSAGINGMETADATA:SCHEDULE:" + msgType + ":")
				.length();
		log.debug("Start index =" + startIndex);
		int endIndex = msg.indexOf(":", startIndex);
		log.debug("End index =" + endIndex);
		String newSchId = msg.substring(startIndex, endIndex);
		log.debug("New id =" + newSchId);
		newSchedule = new CayenneModel<Schedules>(new ScheduleDAO(
				EduShareSession.get().getSessionORMInterface())
				.getScheduleById(Integer.valueOf(newSchId)));

		if (msgType == ScheduleMessage.EVT_MODIFY) {
			startIndex = endIndex + 1;
			endIndex = msg.indexOf(">", startIndex);
			oldTitle = msg.substring(startIndex, endIndex);
		}
	}

	public void initMessage() {
		if (msgType == ScheduleMessage.NEW_EVENT) {
			message = "A new event <strong>'"
					+ newSchedule.getObject().getSchTitle()
					+ "'</strong> was added by "
					+ msg.getObject().getUser().getCompleteUserName()
					+ ". Event summary:<br/>";

		} else if (msgType == ScheduleMessage.EVT_CANCELLED) {
			message = "The event <strong>'"
					+ newSchedule.getObject().getSchTitle()
					+ "'</strong> has been cancelled.";
		} else if (msgType == ScheduleMessage.EVT_MODIFY) {
			message = "The event <strong>'" + oldTitle + "'</strong>"
					+ " has been modified. New event summary:<br/>";
		}
	}

	public Fragment getFragment() {
		if (msgType != ScheduleMessage.EVT_CANCELLED) {
			Fragment table = new Fragment("table", "tab",
					ScheduleMessagePanel.this);
			table.add(new DateLabel("start", newSchedule.getObject()
					.getSchStart(), 0));
			table.add(new DateLabel("end", newSchedule.getObject().getSchEnd(),
					0));

			table.add(new Label("location", newSchedule.getObject()
					.getSchLocation()));
			WebMarkupContainer wmc = null;
			table.add(wmc = new WebMarkupContainer("repeatRow"));
			wmc
					.setVisible(newSchedule.getObject().getFrequency() != Schedules.EVENT_ONCE_ONLY);
			wmc.add(new Label("repeatString", new IModel<String>() {
				private static final long serialVersionUID = 1L;

				public String getObject() {
					switch (newSchedule.getObject().getFrequency()) {
					case Schedules.EVENT_WEEKLY:
						return "Every week till "
								+ new SimpleDateFormat("MMM d, yyyy hh:mm a")
										.format(newSchedule.getObject()
												.getRepetitionEnd());
					case Schedules.EVENT_DAILY:
						return "Everyday till "
								+ new SimpleDateFormat("MMM d, yyyy hh:mm a")
										.format(newSchedule.getObject()
												.getRepetitionEnd());
					case Schedules.EVENT_MONTHLY:
						return "Every month till "
								+ new SimpleDateFormat("MMM d, yyyy hh:mm a")
										.format(newSchedule.getObject()
												.getRepetitionEnd());
					}
					return "";
				}

				public void setObject(String arg0) {
				}

				public void detach() {
				}
			}));

			if (msgType == ScheduleMessage.NEW_EVENT
					|| isTitleModified() == false) {
				table.add(wmc = new WebMarkupContainer("titleRow"));
				wmc.setVisible(false);
				wmc.add(new Label("newTitle", ""));
			} else {
				table.add(wmc = new WebMarkupContainer("titleRow"));
				wmc.add(new Label("newTitle", newSchedule.getObject()
						.getSchTitle()));
			}
			return table;
		}
		return new Fragment("table", "dummy", ScheduleMessagePanel.this);
	}

	public boolean isTitleModified() {
		if (oldTitle.compareTo(newSchedule.getObject().getSchTitle()) == 0) {
			return false;
		} else
			return true;
	}

	private String message = "";
	private String msgType = "";
	private String oldTitle = "";
	private IModel<Schedules> newSchedule = null;
	private IModel<Messages> msg = null;
	private static final long serialVersionUID = 6294154012973596456L;
}
